<?php
class Bizprofile_UserController extends Zend_Controller_Action {
	
	protected $_general_info = array(
		    'contact_email'       => 1,
		    'contact_tel'         => 1,
		    'contact_fax'         => 1,
		    'contact_address'     => 1,
		    'bank_account_vnd'    => 1,
		    'bank_account_usd'    => 1,
		    'registration_number' => 1,
		    'professional'        => 1
	);
    protected $_enterprise_info = array(1,1,1,1,1);
	
    /**
     * This fucntion is not use
     * @author startech
     */
    public function index_NOTUSET_Action() {
        $auth = Zend_Auth::getInstance();
        $user = null;
        if ($auth->hasIdentity()) {
            $user = $auth->getIdentity();
            $this->view->assign('user', $user);
        }
        else{
            $this->_redirect($this->view->serverUrl() . $this->view->url(array(), 'bizprofile_auth_login'));
        }
    }

    /**
    * Register an normal user
    * @return void
    * @author startech
    */
    public function registerAction() {
    	$request = $this->getRequest();
		
    	$auth = Zend_Auth::getInstance();
		$userSession = $auth->getIdentity();	
		
		//Check no login yet		
		if (!$userSession)
		{
	        $conn = Tomato_Db_Connection::factory()->getMasterConnection();
	        $roleDao = Tomato_Model_Dao_Factory::getInstance()->setModule('bizprofile')->getRoleDao();
	        $userDao = Tomato_Model_Dao_Factory::getInstance()->setModule('bizprofile')->getUserDao();
	        $roleDao->setDbConnection($conn);
	        $userDao->setDbConnection($conn);	        
	        
         	//User enterprise models access to data        
	        $userAccountDao = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getUserDao();
	        $userAccountDao->setDbConnection($conn);
	        
	        if ($request->isPost()) {
	        	//Get role id is customer
	            $role = $userAccountDao->getRoleByName('nguoi tieu dung');
	            if(!$role){die('Not found role id');}
	            
                $roleId = $role->role_id;	            
	            $fullname     = $request->getPost('full_name');
	            $username     = $request->getPost('email');
	            $password     = $request->getPost('password');
	            $email        = $request->getPost('email');
	            $created_date = date('Y-m-d H:i:s');
	
	            $user = new Core_Models_User(array(
	                'user_name'      => $username,
	                'password'       => $password,
	                'full_name'      => $fullname,
	                'email'          => $email,
	                'is_active'      => 0,
	                'created_date'      => $created_date,
	                'logged_in_date' => null,
	                'is_online'      => 0,
	                'role_id'          => $roleId,
	            ));
	            $id = $userDao->add($user);
	            
	            //$this->_helper->getHelper('FlashMessenger')->addMessage($this->view->translator('user_register_success'));          
	        	$user_register_success = 1;
	        	$this->view->assign('user_register_success', $user_register_success);
	            
	            if ($id > 0) {	
	                //Send email	                
	                $mailContent1 = $this->view->translator("user_activate_content_mail");
	
	                $time = md5(strtotime($created_date));
	                $arrRoute = array(
	                    'id'       => $id,
	                    'date' 	   => $time
	                );
	                $url = $this->view->serverUrl().$this->view->url($arrRoute,'bizprofile_user_activate');
	                
	                $string = $url;
	                $pattern = '/%40(?=)/';
					$replacement = '@';
					$url = preg_replace($pattern, $replacement, $string);
	
	                $mailContent = $this->view->translator("user_activate_content_mail1");
	                $mailContent .= sprintf($this->view->translator("user_activate_content_mail2"), $url, $url);
	                $mailContent .= $this->view->translator("user_activate_content_mail3");
	
	                $from = "info@kinhdoanhdientu.vn";
	                $from_name = "kinhdoanhdientu.vn";
	               	$to = "{$email}";
	                $bcc = "quan.vo@startech.vn";
	                $content = $mailContent;
	                $subject = $this->view->translator('user_activate_subject');
	                
	                $transport = Mail_Services_Mailer::getMailTransport();
	                $mail = new Zend_Mail('utf-8');
	                $mail->setFrom($from, $from_name)
	                    ->addTo($to)
	                    ->addBcc($bcc)
	                    ->setSubject($subject)
	                    ->setBodyHtml($content)
	                    ->send($transport);
	            }
	        }
		}
		else 
		{
			$this->_redirect($this->view->serverUrl() . $this->view->url(array(), 'bizprofile_dashboard_index'));
		}
    }

    /**
    * Check user exist or not    
    * return: void
    * @author startech
    */
    public function checkAction(){
        $this->_helper->getHelper('viewRenderer')->setNoRender();
        $this->_helper->getHelper('layout')->disableLayout();

        $request   = $this->getRequest();
        $checkType = $request->getParam('check_type');
        $original  = $request->getParam('original');
        $value        = $request->getParam($checkType);

        $conn = Tomato_Db_Connection::factory()->getMasterConnection();
        $userDao = Tomato_Model_Dao_Factory::getInstance()->setModule('bizprofile')->getUserDao();
        $userDao->setDbConnection($conn);

        $result = false;
        if ($original == null || ($original != null && $value != $original)) {
        	
        	/**
        	 * @since 2.0.8
        	 * @author quanvo
        	 */
        	if ($checkType == 'captcha'){  
        		session_start();
        		$captchaId = $request->getParam('captchaId');
		        $captchaInput = $value['input'];		        
		        $captchaIterator = $_SESSION['Zend_Form_Captcha_' . $captchaId];
		        $captchaWord = $captchaIterator ["word"];
		        if ($captchaWord) {
		            if ($captchaInput != $captchaWord) {
						$result = true;
		            } else {
		                $result = false;
		            }
		        }
		        else {
					$result = true;
		        }
        	}
        	else{
        		$result = $userDao->exist($checkType, $value);
        	}
            
        }
        ($result == true) ? $this->getResponse()->setBody('false')
                        : $this->getResponse()->setBody('true');
    }

    /**
    * Register an enterprise
    * @return void
    * @author startech
    */
    public function registerEnterpriseAction(){

        $request = $this->getRequest();

        $conn = Tomato_Db_Connection::factory()->getMasterConnection();

        /**
         * User model access to data
         **/
        $userDao = Tomato_Model_Dao_Factory::getInstance()->setModule('bizprofile')->getUserDao();
        $userDao->setDbConnection($conn);

        /**
         * Role model access to data
         **/
        $roleDao = Tomato_Model_Dao_Factory::getInstance()->setModule('bizprofile')->getRoleDao();
        $roleDao->setDbConnection($conn);

        /**
         * Get Role
         */
        $roles = $roleDao->getRoles();
        $this->view->assign('roles', $roles);

        /**
         * Enterprise model access to data
         **/
        $enterpriseDao = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getEnterpriseDao();
        $enterpriseDao->setDbConnection($conn);

        $is_full = false;
        $count = $enterpriseDao->count(array('deleted' => 0));
        if($count >= 500){
           $is_full = true;
        }
        $this->view->assign('is_full', $is_full);

        /**
         * Get professtions
         **/
        $professions = $enterpriseDao->getProfessions();
        $this->view->assign('professions', $professions);

        /**
        * Currency model access to data
        **/
        $currencyDao = Tomato_Model_Dao_Factory::getInstance()->setModule('bizprofile')->getCurrencyDao();
        $currencyDao->setDbConnection($conn);

        /**
         * Get currency
         **/
        $currency = $currencyDao->getCurrencies();
        $this->view->assign('currency', $currency);

        /**
         * Show Captcha
         */
        $captcha = new Zend_Captcha_Image();
        $captcha->setTimeout('300')
        ->setWordLen('6')
        ->setHeight('60')
        ->setWidth('150')
        ->setFont('images/captcha/fonts/ARIAL.TTF')
        ->setImgDir('images/captcha');
        $captcha->generate();
        $this->view->assign('captchaId', $captcha->getId());

        if ($request->isPost()) {

            /**
            * Check captcha
            */
            if ($request->getPost('captcha') != null && !$this->validateCaptcha($request->getPost('captcha'))) {
                $this->_helper->getHelper ( 'FlashMessenger' )->addMessage ( $this->view->translator ( 'auth_login_user_invalid_captcha' ) );
                $this->_redirect ( $this->view->serverUrl () . $this->view->url ( array (), 'bizprofile_user_register_enterprise' ) );
            }

            $strProfessions = ',';
            $arrId = $request->getPost('professions_id');
            if(count($arrId) > 0){
                foreach($arrId as $row){
                    $strProfessions .= $row.',';
                }
            }

            /**
            * Add new enterprise
            */
            $enterprise = new Enterprise_Models_Enterprise(array(
                'frontend_active'        => 0,
                'backend_active'         => 0,
                'company_name_vn'        => $request->getPost('company_name_vn'),
                'company_name_en'        => $request->getPost('company_name_en'),
                'contact_email'          => $request->getPost('contact_email'),
                'contact_tel'            => $request->getPost('contact_tel'),
                'contact_fax'            => $request->getPost('contact_fax'),
                'contact_address'        => $request->getPost('contact_address'),
                'bank_name_vnd'          => $request->getPost('bank_name_vnd'),
                'bank_name_usd'          => $request->getPost('bank_name_usd'),
                'bank_account_vnd'       => $request->getPost('bank_account_vnd'),
                'bank_account_usd'       => $request->getPost('bank_account_usd'),
                'bank_account_owner_vnd' => $request->getPost('bank_account_owner_vnd'),
                'bank_account_owner_usd' => $request->getPost('bank_account_owner_usd'),
                'registration_number'    => $request->getPost('registration_number'),
                'registration_date'      => date('Y-m-d', strtotime($this->convertDateFormat($request->getPost('registration_date')))),
                'registration_city'      => $request->getPost('registration_city'),
                'deleted'                => 0,
                'professions_id'         => $strProfessions,
                'currency'               => $request->getPost('currency'),
                'application'            => 1,

            ));
            $enterpriseId = $enterpriseDao->add($enterprise);

            /**
             * Update enterprise id to enterprise_professions
             **/
            if($enterpriseId){
                foreach($arrId as $id){
                    $arrPro = array(
                        'professions_id' =>    $id,
                        'enterprise_id'  =>    $enterpriseId,
                    );
                    $enterpriseDao->updateProfessions($arrPro);
                }
            }

            $this->_helper->getHelper('FlashMessenger')
                        ->addMessage($this->view->translator('bizprofile_user_registerenterprise_add_success'));
            $this->_redirect($this->view->serverUrl() . $this->view->url(array(), 'bizprofile_user_register_enterprise'));
        }
    }

    /**
     * Format date to strtotime function use
     * @return string
     */
    private function convertDateFormat($time){
        $a = explode("/", $time);
        $ts = $a[2].'/'.$a[1].'/'.$a[0];
        return $ts;
    }

    /**
    * Edit genearal info
    *
    * @return: void
    */
    public function editGeneralInfoAction() {
        $request = $this->getRequest();		
        $auth = Zend_Auth::getInstance();
        $user = null;
        if ($auth->hasIdentity()) {
            $user = $auth->getIdentity();
            if($user->enterprise != null){
				/*
					Name: Cong Ngo , Date: 11:44 29/4/2011
					Purpose	: tránh cho ng dùng login với tài khoản này lại sửa được info của tài khoản khác
				*/
				$enterprise_id_edit = $request->getParam("enterprise_id");			
				if($user->enterprise->id != $enterprise_id_edit){				
				  $redirector = Zend_Controller_Action_HelperBroker::getStaticHelper('redirector');
				  $redirector->gotoUrl('');								
				}					
				/* End Edit */
                $this->view->assign('enterprise', $user->enterprise);

                $conn = Tomato_Db_Connection::factory()->getMasterConnection();

                /**
                * User model access to data
                **/
                $userDao = Tomato_Model_Dao_Factory::getInstance()->setModule('bizprofile')->getUserDao();
                $userDao->setDbConnection($conn);

                /**
                * Role model access to data
                **/
                $roleDao = Tomato_Model_Dao_Factory::getInstance()->setModule('bizprofile')->getRoleDao();
                $roleDao->setDbConnection($conn);

                /**
                * Get Role
                */
                $roles = $roleDao->getRoles();
                $this->view->assign('roles', $roles);

                /**
                * Enterprise model access to data
                **/
                $enterpriseDao = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getEnterpriseDao();
                $enterpriseDao->setDbConnection($conn);

                /**
                * Get professtions
                **/
                $professions = $enterpriseDao->getProfessions();
                $this->view->assign('professions', $professions);

                /**
                * Currency model access to data
                **/
                $currencyDao = Tomato_Model_Dao_Factory::getInstance()->setModule('bizprofile')->getCurrencyDao();
                $currencyDao->setDbConnection($conn);

                /**
                * Get currency
                **/
                $currency = $currencyDao->getCurrencies();
                $this->view->assign('currency', $currency);

                if ($request->isPost()) {
                    $strProfessions = ',';
                    $arrId = $request->getPost('professions_id');
                    if(count($arrId) > 0){
                        foreach($arrId as $row){
                            $strProfessions .= $row.',';
                        }
                    }

                    /**
                     * Upload logo
                     **/
                    /*if($request->getPost('imageUrl') && $request->getPost('imageURL') != $user->enterprise->id.'.JPG'){
                        copy($request->getPost('imageUrl'), 'images/logos/'.$user->enterprise->id.'.JPG');
                    }*/
                    $cwd_path = getcwd()."/images/logos/";
                    $name = $user->enterprise->id.'.JPG';
                    $target_path = $cwd_path . basename($name);
                    move_uploaded_file($_FILES['logo']['tmp_name'], $target_path);

                    /**
                    * Update image
                    **/
                    $cwd_path = getcwd()."/images/maps/";
                    $name = $user->enterprise->id.'.png';
                    $target_path = $cwd_path . basename($name);
                    move_uploaded_file($_FILES['map']['tmp_name'], $target_path);


                    /**
                    * Add new enterprise
                    */
                    $enterprise = new Enterprise_Models_Enterprise(array(
                        'frontend_active'        => $user->enterprise->frontend_active,
                        'backend_active'         => $user->enterprise->backend_active,
                        'company_name_vn'        => $request->getPost('company_name_vn'),
                        'company_name_en'        => $request->getPost('company_name_en'),
                        'contact_email'          => $request->getPost('contact_email'),
                        'contact_tel'            => $request->getPost('contact_tel'),
                        'contact_fax'            => $request->getPost('contact_fax'),
                        'contact_address'        => $request->getPost('contact_address'),
                        'bank_name_vnd'          => $request->getPost('bank_name_vnd'),
                        'bank_name_usd'          => $request->getPost('bank_name_usd'),
                        'bank_account_vnd'       => $request->getPost('bank_account_vnd'),
                        'bank_account_usd'       => $request->getPost('bank_account_usd'),
                        'bank_account_owner_vnd' => $request->getPost('bank_account_owner_vnd'),
                        'bank_account_owner_usd' => $request->getPost('bank_account_owner_usd'),
                        'registration_number'    => $request->getPost('registration_number'),
                        'registration_date'      => date('Y-m-d', strtotime($this->convertDateFormat($request->getPost('registration_date')))),
                        'registration_city'      => $request->getPost('registration_city'),
                        'deleted'                => 0,
                        'professions_id'         => $strProfessions,
                        'currency'               => $request->getPost('currency'),
                        'application'            => 0,
                        'id'                     => $request->getPost('enterprise_id')
                    ));

                    $enterpriseId = $enterpriseDao->update($enterprise);
                    $user->enterprise = $enterprise;

                    /**
                    * Update enterprise id to enterprise_professions
                    **/
                    if($enterpriseId){

                        $user->enterprise = $enterprise;

                        foreach($arrId as $id){
                            $arrPro = array(
                                'professions_id' =>    $id,
                                'enterprise_id'  =>    $enterpriseId,
                            );
                            $enterpriseDao->updateProfessions($arrPro);
                        }
                    }

                    /*$this->_helper->getHelper('FlashMessenger')
                                ->addMessage($this->view->translator('bizprofile_user_edit_general_info_success'));*/
                    $this->_redirect($this->view->serverUrl() . $this->view->url(array(), 'bizprofile_dashboard_index'));
                }
            }
        }
    }

    /**
    * Edit enterprise info
    *
    */
    public function editEnterpriseInfoAction(){
        $request     = $this->getRequest();
        $info_id     = $request->getParam('info_id');
        $auth = Zend_Auth::getInstance();
        $user = null;
        if ($auth->hasIdentity()) {
            $user = $auth->getIdentity();
            if(isset($user->enterprise)){				
				/*
					Name: Cong Ngo , Date: 11:44 29/4/2011
					Purpose	: tránh cho ng dùng login với tài khoản này lại sửa được info của tài khoản khác
				*/
				$enterprise_id_edit = $request->getParam("enterprise_id");			
				if($user->enterprise->id != $enterprise_id_edit){				
				  $redirector = Zend_Controller_Action_HelperBroker::getStaticHelper('redirector');
				  $redirector->gotoUrl('');								
				}					
				/* End Edit */
			
                $conn = Tomato_Db_Connection::factory()->getMasterConnection();
                $infoDao  = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getInfoDao();
                $infoDao->setDbConnection($conn);
                $info = $infoDao->getById($info_id);
                $this->view->assign('info', $info);

                if ($request->isPost()) {
                    $content           = $request->getPost('content');
                    $info = new Enterprise_Models_Info(array(
                        'info_string'            => $content,
                        'info_id'                => $info_id,
                        'enterprise_id'            => $user->enterprise->id,
                        'language'                => $info->language,
                        'info_title'            => $info->info_title,
                        'info_number'            => $info->info_number,
                    ));

                    $id = $infoDao->update($info);

                    if($id){
                        /*$this->_helper->getHelper('FlashMessenger')
                                    ->addMessage($this->view->translator('bizprofile_user_edit_enterprise_info_success'));*/
                        $this->_redirect($this->view->serverUrl() . $this->view->url(array(), 'bizprofile_dashboard_index'));
                    }
                }
            }
        }
    }

    /**
    * Add enterprise info
    *
    */
    public function addEnterpriseInfoAction(){
//        /*$request     = $this->getRequest();
//
//        $auth = Zend_Auth::getInstance();
//        $user = null;
//        if ($auth->hasIdentity()) {
//            $user = $auth->getIdentity();
//
//            if($user->enterprise){
//                $this->view->assign('enterprise', $user->enterprise);
//
//                $conn = Tomato_Db_Connection::factory()->getMasterConnection();
//                $infoDao  = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getInfoDao();
//                $infoDao->setDbConnection($conn);
//
//                //Check maximum 5 tab
//                $infoDao->setLang( $request->getParam('lang'));
//                $infos = $infoDao->getInfos($user->enterprise->id, 5);
//                if(count($infos) == 5){
//                    $this->_redirect($this->view->serverUrl() . $this->view->url(array(), 'bizprofile_dashboard_index'));
//                }
//
//                /**
//                 * @since 2.0.8
//                 */
//                $sourceId       = $request->getParam('source_id');
//                $sourceInfo     = (null == $sourceId) ? null : $infoDao->getById($sourceId);
//                if($sourceInfo != null){
//                    $sourceInfo->title = $sourceInfo->info_title;
//                    $sourceInfo->content = $sourceInfo->info_string;
//                }
//                $this->view->assign('translatableData', (null == $sourceInfo) ? array() : $sourceInfo->getProperties());
//                $this->view->assign('sourceInfo', $sourceInfo);
//                $this->view->assign('lang', $request->getParam('lang'));
//
//                if ($request->isPost()) {
//                    $title           = $request->getPost('title');
//                    $content           = $request->getPost('content');
//                    $number            = $request->getPost('number');
//                    $info = new Enterprise_Models_Info(array(
//                        'info_title'             => strip_tags($title),
//                        'info_string'            => $content,
//                        'info_number'            => $number,
//                        'enterprise_id'            => $user->enterprise->id,
//                        'language'                => $request->getPost('languageSelector'),
//                    ));
//
//                    $infoId = $infoDao->add($info);
//
//                    /**
//                     * @since 2.0.8
//                     */
//                    $source = Zend_Json::decode($request->getPost('sourceItem', '{"id": "", "language": ""}'));
//                    $translationDao = Tomato_Model_Dao_Factory::getInstance()->setModule('core')->getTranslationDao();
//                    $translationDao->setDbConnection($conn);
//                    $translationDao->add(new Core_Models_Translation(array(
//                        'item_id'           => $infoId,
//                        'item_class'      => get_class($info),
//                        'source_item_id'  => ('' == $source['id']) ? $infoId : $source['id'],
//                        'language'        => $info->language,
//                        'source_language' => ('' == $source['language']) ? null : $source['language'],
//                    )));
//
//                    if($infoId){
//                        /*$this->_helper->getHelper('FlashMessenger')
//                                      ->addMessage($this->view->translator('bizprofile_user_add_enterprise_info_success'));*/
//                        $this->_redirect($this->view->serverUrl() . $this->view->url(array(), 'bizprofile_dashboard_index'));
//                    }
//                }
//            }
//        }*/
    }

    public function editPermissionAction() {
        $request     = $this->getRequest();
        $auth = Zend_Auth::getInstance();
        $user = null;
        if ($auth->hasIdentity()) {
            $user = $auth->getIdentity();
            if($user->enterprise){
				/*
					Name: Cong Ngo , Date: 11:44 29/4/2011
					Purpose	: tránh cho ng dùng login với tài khoản này lại sửa được info của tài khoản khác
				*/
				$enterprise_id_edit = $request->getParam("enterprise_id");			
				if($user->enterprise->id != $enterprise_id_edit){				
				  $redirector = Zend_Controller_Action_HelperBroker::getStaticHelper('redirector');
				  $redirector->gotoUrl('');								
				}					
				/* End Edit */
			
                $this->view->assign('enterprise', $user->enterprise);

                $conn = Tomato_Db_Connection::factory()->getMasterConnection();
                $permissionDao = Tomato_Model_Dao_Factory::getInstance()->setModule('bizprofile')->getPermissionDao();
                $permissionDao->setDbConnection($conn);
                $roles = $permissionDao->getRoles();
                $this->view->assign('roles', $roles);
                if ($request->isPost()) {
                    foreach ($roles as $role){
                        $blog_permission = $request->getPost("blog_permission_".$role->role_id) == 'on' ? 1 : 0 ;
                        $media_permission = $request->getPost("media_permission_".$role->role_id) == 'on' ? 1 : 0;
                        $partner_permission = $request->getPost("partner_permission_".$role->role_id) == 'on' ? 1 : 0 ;
                        $messaging_permission = ($request->getPost("messaging_permission_".$role->role_id) == 'on') ? 1 : 0;
                        $general_infos = array();
                        foreach ($this->_general_info as $key => $value){
                            $general_infos[$key] = $request->getPost("general_info_".$key."_".$role->role_id) == 'on' ? 1 : 0;
                        }
                        $enterprise_infos = array();
                        foreach ($this->_enterprise_info as $key => $value){
                            $enterprise_infos[$key] = $request->getPost("enterprise_info_".$key."_".$role->role_id) == 'on' ? 1 : 0;
                        }
                        $permission = new Bizprofile_Models_Permission(array(
                            'enterprise_id'              => $user->enterprise->id,
                            'user_entity'                 => $role->role_id,
                            'general_info'                   => serialize($general_infos),
                            'enterprise_info'               => serialize($enterprise_infos),
                            'media_permission'               => $media_permission,
                            'blog_permission'               => $blog_permission,
                            'partner_permission'          => $partner_permission,
                            'messaging_permission'          => $messaging_permission
                        ));
                        $permissionDao->update($permission);
                    }
                }
                $permissions = $permissionDao->getPermission($user->enterprise->id);
                if($permissions->count() == 0){
                    foreach ($roles as $role){
                        $permission = new Bizprofile_Models_Permission(array(
                            'enterprise_id'                 => $user->enterprise->id,
                            'user_entity'                   => $role->role_id,
                            'general_info'                  => serialize($this->_general_info),
                            'enterprise_info'               => serialize($this->_enterprise_info),
                            'media_permission'              => 1,
                            'blog_permission'               => 1,
                            'partner_permission'            => 1,
                            'messaging_permission'          => 1
                        ));
                        $permissionDao->add($permission);
                    }
                    $permissions = $permissionDao->getPermission($user->enterprise->id);
                }
                $this->view->assign('permissions', $permissions);
                $this->view->assign('general_info', $this->_general_info);
                $this->view->assign('enterprise_info', $this->_enterprise_info);
                
            }
        }
    }

    public function activateAction(){
        $request = $this->getRequest();
        $auth = Zend_Auth::getInstance();
        if ($auth->hasIdentity()) {
            $this->_redirect($this->view->serverUrl());
        }
        else{        	
            /**
            * Get connaction to database
            **/
            $conn = Tomato_Db_Connection::factory()->getMasterConnection();

            /**
            * Bizprofile_Models_User access to data
            **/
            $userDao = Tomato_Model_Dao_Factory::getInstance()->setModule('bizprofile')->getUserDao();
            $userDao->setDbConnection($conn);

            $id   = $request->getParam('id');
            $date = $request->getParam('date');
            
            $user = $userDao->getById($id);            
            $created_date = strtotime(@$user->created_date);

            $flag = '';
            if(@$user->is_active != 1){            	
                if(md5($created_date) == $date){
                    $expire = 3*24*60*60;
                    $dateDelay = time()-$created_date;
                    if($dateDelay <= $expire){			
                        $userDao->toggleStatus($id);
                        $flag = 'activate_done';                       
                    }
                    else{
                        $created_date = date('Y-m-d H:i:s');

                        /**
                        * Update created date
                        **/
                        $void = $userDao->updateCDate($id, $created_date);

                        /**
                        * Send email
                        */
                        if($void){
                            $flag = "expired";

                            $time = md5(strtotime($created_date));
                            $arrRoute = array(
                                'id'   => $id,
                                'date' => $time
                            );
                            $mailContent = $this->view->translator("user_activate_content_mail1");
                            $mailContent .= sprintf($this->view->translator("user_activate_content_mail2"), $url, $url);
                            $mailContent .= $this->view->translator("user_activate_content_mail3");

                            $email = $user->email;
                            $from = "info@kinhdoanhdientu.vn";
                            $from_name = "kinhdoanhdientu.vn";
                            $to = "{$email}";
                            $bcc = "quan.vo@startech.vn";
                            $content = $mailContent;
                            $subject = $this->view->translator('user_activate_subject');
                            $transport = Mail_Services_Mailer::getMailTransport();
                            $mail = new Zend_Mail('utf-8');
                            $mail->setFrom($from, $from_name)
                                ->addTo($to)
                                ->addBcc($bcc)
                                ->setSubject($subject)
                                ->setBodyHtml($content)
                                ->send($transport);
                        }
                        else{
                            echo "NO UPDATE";die;
                        }
                    }
                }
                else{
                    $flag = 'invalid';
                }
            }
            else{
                $flag = 'is_activate';                
            }
            $this->view->assign('flag', $flag);
        }
    }

    public function captchaAction(){
    	$this->_helper->getHelper('viewRenderer')->setNoRender();
        $this->_helper->getHelper('layout')->disableLayout();
        
        $captcha = new Zend_Captcha_Image();
        $captcha->setTimeout('300')
        ->setWordLen('6')
        ->setHeight('45')  // image height
        ->setWidth('137')  //  image width
        ->setFont('images/captcha/fonts/ARIAL.TTF')  // use this font to create the word
        ->setFontSize(15)  // font size
        ->setImgDir('images/captcha')  // save the image here
        ->setLineNoiseLevel(0)  // sets the line noise
        ->setDotNoiseLevel(10)  // sets the dot nois
        ->setExpiration(100)
        ->setGcFreq(100);
        $captcha->generate();
        
        $captchaWord = 'abc';
        $captchaId = $captcha->getId();
        $arrResult = array(
            'word' => $captchaWord,
            'id'   => $captchaId
        );
        $strResult =  $captchaId.';;'.$captchaWord;        
        $this->getResponse()->setBody($strResult);        
    }
    

    /**
    * Validates captcha response
    *
    * @param string $captcha
    * @return boolean
    */
    private function validateCaptcha($captcha) {
        $captchaId = $captcha ["id"];
        $captchaInput = $captcha ["input"];
        $captchaSession = new Zend_Session_Namespace ( "Zend_Form_Captcha_" . $captchaId );
        $captchaIterator = $captchaSession->getIterator ();
        $captchaWord = $captchaIterator ["word"];
        if ($captchaWord) {
            if ($captchaInput != $captchaWord) {
                return false;
            } else {
                return true;
            }
        } else {
            return false;
        }
    }
    
    
    /**=============================================QuanVo======================================*/
    public function testcaptchaAction(){
    	//$this->_helper->getHelper('viewRenderer')->setNoRender();
        //$this->_helper->getHelper('layout')->disableLayout();
		
        $img = new Tomato_Helper_Captcha_Securimage();
        echo "<pre>";
        print_r($img);
        echo "<pre>";
        exit();
		//Change some settings
		$img->image_width = 150;
		$img->image_height = 30;
		$img->perturbation = 0.7;
		$img->num_lines = 0;
		/*$img->image_bg_color = new Securimage_Color("#f6f6f6");
		$img->multi_text_color = array(new Securimage_Color("#3399ff"),
		                               new Securimage_Color("#3300cc"),
		                               new Securimage_Color("#3333cc"),
		                               new Securimage_Color("#6666ff"),
		                               new Securimage_Color("#99cccc")
		                               );*/
		//$img->use_multi_text = true;
		//$img->text_angle_minimum = -5;
		//$img->text_angle_maximum = 5;
		//$img->use_transparent_text = true;
		//$img->text_transparency_percentage = 30; // 100 = completely transparent
		//$img->num_lines = 0;
		//$img->line_color = new Securimage_Color("#555555");
		//$img->image_signature = 'phpcaptcha.org';
		//$img->signature_color = new Securimage_Color(rand(0, 64), rand(64, 128), rand(128, 255));
		//$img->use_wordlist = true; 
		
		//$img->show('backgrounds/bg3.jpg'); // alternate use:  $img->show('/path/to/background_image.jpg');		
		$img->show('backgrounds/bg_none.jpg'); // alternate use:  $img->show('/path/to/background_image.jpg');		
    }
}